package cn.dengta.webapp.user.form;

import cn.dengta.common.context.I18N;
import cn.dengta.common.security.SecurityUtil;
import cn.dengta.common.validator.*;
import cn.dengta.common.web.Client;
import cn.dengta.context.model.AppContext;
import cn.dengta.context.model.UserFormI18nKey;
import cn.dengta.webapp.base.entity.ChannelAppType;
import cn.dengta.webapp.user.entity.ClientInfo.LoginWay;
import cn.dengta.webapp.user.entity.OauthUser;
import cn.dengta.webapp.user.model.CredentialType;
import lombok.*;
import lombok.experimental.Accessors;
import me.codeplayer.util.StringUtil;

/**
 * 【用户登录】
 */
@Getter
@Setter
@Accessors(chain = true)
public class UserLoginForm implements Form {

	/** 用户名/手机号/邮箱 */
	@Check(UserFormI18nKey.USER_LOGIN_FORM_USERNAME)
	@Trim
	@NotEmpty
	public String username;
	/** 密码（与 短信验证码 二选一） */
	@Check(value = UserFormI18nKey.USER_LOGIN_FORM_PASSWORD, required = false)
	@Trim
	@NotEmpty
	@Size(min = 6)
	public String password;
	/** 验证码（与 密码 二选一） */
	@Check(value = UserFormI18nKey.USER_LOGIN_FORM_CAPTCHA, required = false)
	@Trim
	@NotEmpty
	public String captcha;
	/** 是否启用记住我（自动登录） */
	public int rememberMe = 1;
	public Integer forceLogin;
	//
	@Setter(AccessLevel.NONE)
	public Client client;
	@Setter(AccessLevel.NONE)
	public OauthUser oauthUser;
	@Setter(AccessLevel.NONE)
	public LoginWay loginWay;
	@Setter(AccessLevel.NONE)
	public boolean fromBackstage;
	public String inviteCode;
	public String agentCode;
	@Setter(AccessLevel.NONE)
	public boolean fromAuth = false;

	/** 广告ID */
	@Check(value = "advertId", required = false)
	@Trim
	public String advertId;
	/** Adjust 设备 ID */
	@Check(value = "adid", required = false)
	@Trim
	public String adid;
	/** ios 设备 */
	public String idfv;
	/** androidId */
	public String androidId;
	/** 投放应用：ad，af */
	public ChannelAppType adType;

	/** 应用市场渠道包名 */
	@Setter(AccessLevel.NONE)
	public String channel;
	/** 登录版本号 */
	@Setter(AccessLevel.NONE)
	public String version;

	@Override
	public void preHandle() {
		username = SecurityUtil.defendXSS(StringUtil.trim(username));
		if (StringUtil.notEmpty(password)) {
			loginWay = LoginWay.BY_PASSWORD;
		} else if (StringUtil.notEmpty(captcha)) {
			CredentialType credentialType = CredentialType.identify(username);
			loginWay = credentialType == CredentialType.PHONE ? LoginWay.BY_CAPTCHA : LoginWay.BY_MAIL_CAPTCHA;
		} else {
			throw new IllegalArgumentException(I18N.msg(UserFormI18nKey.USER_LOGIN_FORM_CREDENTIAL_REQUIRED));
		}
	}

	public UserLoginForm init(LoginWay loginWay, Client client, boolean fromBackstage) {
		this.loginWay = loginWay;
		this.client = client;
		this.fromBackstage = fromBackstage;
		return this;
	}

	public void setAdType(String adType) {
		this.adType = ChannelAppType.of(adType);
	}

}
